<template>
	<div style="padding:0 37px 0 44px" class="main-container-div">
    
    <div class="breadcrumb-father">
      <div class="new-breadcrumb">
        <router-link  :to="{path:'/welcome'}">
          <img src="../../../assets/imgs/Home.png" alt="">
        </router-link>
          <span>{{$t('mer.Client')}}</span>
          <span class="arrow">></span>
          <span>{{$t('agent.agent')}}</span>
      </div>
    </div>


		<div class="card-table">
			<div class="card-table-title">
        <svg aria-hidden="true" class="svg-icon svg-title-icon">
          <use xlink:href="#icon-dailishang"></use>
        </svg>
				<span>{{ $t('agent.agent') }}</span>
			</div>
			<div>
			<!--搜索输入框-->
				<div class="search">
					<div class="search-input">
            <div class="date-wrapper">
                <label for="">{{$t('other.EstablishmentFrom2')}}</label>
                <div class="date-line"></div>
                <el-date-picker :editable=false value-format="yyyy-MM-dd" clearable type="date" placeholder="" @keyup.enter.native="search(0)" v-model="searchAgentData.startDate"></el-date-picker>
						</div>
						<div>
							<label for="">{{$t('other.EstablishmentTo')}}</label>
							<el-date-picker :editable=false value-format="yyyy-MM-dd" clearable type="date" placeholder="" @keyup.enter.native="search(0)" v-model="searchAgentData.endDate"></el-date-picker>
						</div>

						<div>
							<label>{{ $t('newcash.agentName') }}</label>
							<el-input v-model="searchAgentData.dName" clearable :maxlength=100 @keyup.enter.native="search(0)" :placeholder="userType==='2'?dis_name:''" ></el-input>
						</div>
						<div>
							<label>{{ $t('search.levelID1') }}</label>
							<el-input v-model="searchAgentData.distributorId" clearable :maxlength=15 @keyup.enter.native="search(0)"></el-input>
						</div>
						<div class="shangji" v-if="userType != '8'" >
							<label>{{ $t('search.UpperLevel') }}</label>
							<!-- <el-input v-model="searchAgentData.pdName" :maxlength=100 @keyup.enter.native="search(0)"></el-input> -->
              <el-select v-model="searchAgentData.pdName" popper-class='selectMer' filterable clearable :placeholder="$t('placeH.All')" :maxlength=100>
                  <el-option v-for="item in pdNameOptions" :key="item.id" :label="item.name" :value="item.name"></el-option>
              </el-select>
						</div>
						<div>
							<label>{{ $t('search.Status2') }}</label>
							<el-select v-model="searchAgentData.state" popper-class="el-select-custom" :placeholder="$t('placeH.All')" clearable @keyup.enter.native="search(0)"  class='filter-item condition'>
								<el-option :label="$t('search.Rejected')" value=0></el-option>
								<el-option :label="$t('search.Pending')" value=1></el-option>
								<el-option :label="$t('button.Suspended3')" value=3></el-option>
								<el-option :label="$t('button.Enabled')" value=2></el-option>
							</el-select>
						</div>

						<div class="search-btn-group">
                <el-button class="blue-btn mini2-btn" @click="search(0)">{{ $t('button.search') }}</el-button>
                <el-button class="blue-btn mini2-btn" @click="delSelect()">{{ $t('button.Reset') }}</el-button>
            </div>
					</div>

				</div>
				<!--代理商表单-->
				<template>
					<div class="table-border">
                        <div class="search-result-head">
                            <span>{{ searchInfo }}</span>
                            <span style="float:right;">
                                <a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')"><icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg></a>
                                <a href="javascript:void(0)" v-if="userType === '2' " @click="showAgentAdd()" :title="$t('button.New')"><icon-svg icon-class="jia"></icon-svg></a>
                            </span>
                        </div>
						<el-table border :data="agentDatas" height=500 @cell-mouse-enter="showHandle" @cell-mouse-leave="hiddenHandle" v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
							<el-table-column type="index" fixed :label="$t('index.Number')" width="80">						    	
							</el-table-column>
							<el-table-column prop="name" :label="$t('newcash.agentName')" class-name="title_name" width="150">						    	
							</el-table-column>
							<el-table-column prop="distributorNumber" :label="$t('search.levelID1')" width="120">						    	
							</el-table-column>
							<el-table-column prop="state" :label="$t('search.Status2')" :formatter="modifyState" width="200">						    	
							</el-table-column>
                            <el-table-column prop="balance" :label="$t('mer.AccountBalance')" width="200" :formatter="judgeBalance">
                            </el-table-column>
                            <el-table-column v-if="companyId==='2'?false:true" prop="endamt" :label="$t('mer.AvailableBalance')" width="200" :formatter="judgeEndamt">
                            </el-table-column>
                            <el-table-column v-if="companyId==='2'?false:true" prop="freezeamt" :label="$t('trade.frozenAmount')" width="220" :formatter="judgeFreezeamt">
                            </el-table-column>
							<el-table-column prop="parentName" :label="$t('search.UpperLevel2')" width="200"> 
							</el-table-column>
							<el-table-column prop="merchantAmount" :label="$t('agent.DirectMerchants')" width="200">						    
							</el-table-column>
							<!-- <el-table-column prop="salesmanAmount" :label="$t('agent.BDStaff')" width="120">						    	
							</el-table-column> 业务员数 -->
							<el-table-column prop="subordinateAmount" :label="$t('agent.SubordinateAgents')" width="220">						    	
							</el-table-column>
							<el-table-column prop="addedDate" :label="$t('mec.CreationTime1')" width="200">
							</el-table-column>
                            <el-table-column fixed="right" class-name="animate_td handle-hidden-3">
                                        <template slot-scope="scope">
                                <a class="svg-link-class" :title="$t('button.Manage')" @click='showAgentDtails(scope.row.id,scope.row.state,scope.row.name,scope.row.grade,scope.row.parentId)'>
                                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-yonghu"></use></svg>
                                </a>
                                <a class="svg-link-class" :title="$t('button.Enabled1')" v-if="scope.row.state==='3' && userType === '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click='stopOrStart(scope.row.state,scope.row.enabled,scope.row.id,scope.row.userId)'>
                                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-qiyong"></use></svg>
                                </a>
                                <a class="svg-link-class" :title="$t('button.Suspended1')" v-if="scope.row.state==='2' && userType === '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946'  " @click='stopOrStart(scope.row.state,scope.row.enabled,scope.row.id,scope.row.userId)'>
                                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-stop"></use></svg>
                                </a>
                                <!-- <a class="svg-link-class" :title="$t('button.delete')" v-if="scope.row.state==='0'" @click='del(scope.row.id)'>
                                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-shanchu"></use></svg>
                                </a> -->
                                </template>
                            </el-table-column>
						</el-table>
					</div>
				</template>
			</div>
		</div>
		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" background @current-change="handleCurrentChange" :current-page.sync="searchAgentData.page" :page-sizes="[15,20,30,50]" :page-size="searchAgentData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
		</div>
	</div>
</template>

<script>
import { agentManage } from "views/z_businessManagement/components";
import { searchDistributor } from "api/businessManagement/merchant/index";
import {
  createAgent,
  agentAll,
  agentDetails,
  modifyAgent,
  updateStateAgent,
  delAgent
} from "api/merchant/agent/index";
export default {
  name: "agent",
  // components: { agentManage },
  data() {
    return {
      id: null, //根据父组件传递的id 判断用户操作为查看详情 或是新增
      companyId:localStorage.getItem('companyId'),
      userType:localStorage.getItem('userType'),
      userPhone:localStorage.getItem('phone'),
      grade:localStorage.getItem('grade'),
      distributorId:localStorage.getItem('distributorId'), //代理商id
      salesmanId:localStorage.getItem('salesmanId'),
      firmId:localStorage.getItem('firmId'),
      state: null,
      res: [],
      searchAgentData: {
        page: 1 ,
        pageSize: 15,
        dName: null,
        pdName: null,
        distributorId: null,
        date: null,
        state: undefined,
        startDate: null,
        endDate: null,
      },
      agentDatas: [], //代理商列表
      msg: "",
      msgAll: "",
      degIndex:1,
      rorateFlag:true,
      last_td_arr:[],
      searchInfo:'',
      dis_name:null,
      currency:undefined,
      pdNameOptions:[],
      oldPage: null,
      loading: true,
    };
  },
  watch:{
    'searchAgentData.page':function(newVal,oldVal){
        this.oldPage = oldVal;
    },
  },
  created() {
    // this.searchAgentData.page = this.$route.query.page ? +this.$route.query.page : 1;
    // this.searchAgentData.pageSize = this.$route.query.pageSize ? +this.$route.query.pageSize : 15;
    if(localStorage.getItem('searchAgentData')){
      this.searchAgentData = JSON.parse(localStorage.getItem('searchAgentData'));
    }

    this.getAgentList(this.searchAgentData);
    this.searchInfo = this.$t('agent.agent');

    // 查询所属代理商
    this.searchDistributor();

    $("#z_businessManagement .el-menu a li:eq(1)").addClass('is-active');

    if (this.companyId == '1') this.currency = 'HK$ ';
    if (this.companyId == '2') this.currency = 'A$ ';
  },
  methods: {
    searchDistributor() {
      let searchData = {};
      if(this.userType == 2 && this.grade > 0) {
        searchData.distributorId = this.distributorId;
      }else if(this.userType == 5 || this.userType == 9 || this.grade == 0 || this.userType == 0 || this.userType == 11 ) {
        searchData.companyId = this.companyId;
      }else if(this.userType == 10) {
        searchData.firmId = this.firmId;
      }else if(this.userType == 8) {
        searchData.salesmanId = this.salesmanId;
      }

      searchDistributor(searchData)
        .then(res => {
          if (res.code == 0) {
            // console.log("查询所属代理商返回数据：" + res);
            this.pdNameOptions = res.value;
          }
        })
        .catch(() => {});
    },
    showHandle(row, column, cell, event){
      // console.log(row);
      for(let i = 0;i<this.agentDatas.length;i++){
        if(this.agentDatas[i].id === row.id){
          this.tableIndex = i;
          const table_row = $(".el-table__fixed-right").find('.el-table__row')[i];
          $(table_row).find('td:last').removeClass('handle-hidden-'+ this.last_td_arr[i] );
          $(".el-table__fixed-right").addClass("fixed-column-" + this.last_td_arr[i] );
          $(".el-table__fixed-right").css("z-index","22");
          var action_div = $(table_row).find('td:last').children("div");
          $(action_div).stop().animate({"right": "0"});
        }
      }
      // 判断项目数目是否导致滚动条出现
      if(this.agentDatas.length <= 15){
        $(".el-table__fixed-right").addClass("right-zero");
      }else{
          $(".el-table__fixed-right").removeClass("right-zero");
      }
    },
    hiddenHandle(row, column, cell, event){
      const table_row = $(".el-table__fixed-right").find('.el-table__row')[this.tableIndex];
      $(".el-table__fixed-right").css("z-index","0");
      var action_div = $(table_row).find('td:last').children("div");
      $(action_div).stop().animate({"right": "-360px"});
    },
    //刷新数据
    refresh(){
      const _that = this;
      if(this.rorateFlag){
        document.getElementById('refresh_icon').style.transform = 'rotate('+ this.degIndex * 360 +'deg)';
        this.search(1);
        this.rorateFlag = false;
        setTimeout(function (param) { _that.rorateFlag = true;_that.degIndex++; },1000);
      }
    },
    selectColor(row) {
      return (this.activeColor = row.enabled === false ? "#D81334" : "#0006FF");
    },
    //格式化显示数据
    modifyState(row) {
      let state = row.state;
      if (state === "0") {
        return (state = this.$t("search.Rejected"));
      } else if (state === "1") {
        return (state = this.$t("search.Pending"));
      } else if (state === "2") {
        return (state = this.$t("button.Enabled"));
      } else if (state === "3") {
        return (state = this.$t("button.Suspended3"));
      }
    },
        //格式化金额
    judgeBalance(row) {
      let formatMoney = row.balance;
      if( this.grade <= 1 ){
        return formatMoney = this.currency + this.fmoney(formatMoney,2)
      } else {
        return formatMoney = '-';
      }
      
    },
    judgeEndamt(row) {
      let formatMoney = row.endamt;
      if( this.grade <= 1 ){
        return formatMoney = this.currency + this.fmoney(formatMoney,2)
      } else {
        return formatMoney = '-';
      }
    },
    judgeFreezeamt(row) {
      let formatMoney = row.freezeamt;
      if( this.grade <= 1 ){
        return formatMoney = this.currency + this.fmoney(formatMoney,2)
      } else {
        return formatMoney = '-';
      }
    },
        // 格式化金额
    fmoney(s, n){   
      if( s === "" || s === undefined ) return s = "0.00";
      s = s / 100;
      n = n > 0 && n <= 20 ? n : 2;   
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
      var l = s.split(".")[0].split("").reverse(),   
      r = s.split(".")[1];   
      let t = "";   
      for(let i = 0; i < l.length; i ++ )   
      {   
          t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
      }   
      return t.split("").reverse().join("") + "." + r;
    },
    //删除代理商
    del(id) {
      delAgent(id).then(res => {
          if (res.code === 0) {
            this.getAgentList(this.searchAgentData);
          }
        })
    },
    //停用或启用该代理商
    stopOrStart(state, enabled, id, userId) {
      // let msg = state === '3' ? this.$t('hint.TheAgentIsEnabled') : this.$t('hint.TheAgentIsDisabled');
      // let msgAll = state === '3' ? this.$t('hint.SureToEnableThisAgent') : this.$t('hint.SureToSuspendThisAgent');
      if (state == "3") {
        this.msg = this.$t("hint.TheAgentIsEnabled");
        this.msgAll = this.$t("hint.SureToEnableThisAgent");
        enabled = true;
      }
      if (state == "2") {
        this.msg = this.$t("hint.TheAgentIsDisabled");
        this.msgAll = this.$t("hint.SureToSuspendThisAgent");
        enabled = false;
      }
      let modifyEnabled = { id: id, userId: userId, enabled: enabled };
      this.$msgbox({
        title: this.$t("hint.Alert"),
        message: this.msgAll,
        showClose: false,
        closeOnClickModal:false,
        showCancelButton: true,
        confirmButtonText: this.$t("button.OK"),
        cancelButtonText: this.$t("button.Cancel"),
      }).then(() => {
        updateStateAgent(modifyEnabled).then(res => {
          this.getAgentList(this.searchAgentData);
          if (res.code === 0) {
            this.$notify({
              title: this.$t("hint.Success"),
              message: this.msg,
              type: "success",
              duration: 2000
            });
          } else {
            this.getMecList(this.getMecListData);
          }
        });
      });
    },
    //查询全部代理商
    getAgentList(value,str) {
      const _that = this;
      this.last_td_arr = [];
      value.companyId = localStorage.getItem("companyId");
      if( this.grade == 0 ){
        value.pdistributorId = null;
      } else {
        value.pdistributorId = localStorage.getItem("distributorId");
      }
      if( value.pdName ){
        delete value.pdistributorId;
      }
      
      this.formatObj(value);
      agentAll(value).then(res => {
          this.agentDatas = res.value.list;
          this.res = res.value;

          // 特殊处理，防止以下索引取值不到导致载入层隐藏不掉
          setTimeout(function() {
            // 隐藏载入提示层
            _that.loading = false;
          },500)

          this.dis_name = this.grade == '0' ?  localStorage.getItem('userName') : res.value.list[0].parentName;

          // 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
          if( str == 'CurrentChange' ){
            let obj = $('.el-pager .number');
            for( let i = 0; i < obj.length; i++){
                if($(obj[i]).html() == this.searchAgentData.page) {
                  $(obj[i]).addClass('active');
                } else {
                  $(obj[i]).removeClass('active');
                }
            }
          }

          setTimeout(function (param) { 
            const td_last_child = $(".el-table__body-wrapper tr td:last-child");
            for(let i=0;i<td_last_child.length;i++){
              $(td_last_child[i]).removeClass('handle-hidden-3');
            }
            const td_fixed_last_child = $(".el-table__fixed-right tr td:last-child");
            for(let i=0;i<td_fixed_last_child.length;i++){
              // console.log($(td_fixed_last_child[i]).find('.svg-link-class').length);
              if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 1 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-2').addClass('handle-hidden-1');
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 2 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-1').addClass('handle-hidden-2');
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 3 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-1').removeClass('handle-hidden-2').addClass('handle-hidden-3');
							} 
              _that.last_td_arr.push($(td_fixed_last_child[i]).find('.svg-link-class').length);
              
              const title_name_arr = $(".el-table__body-wrapper .title_name .cell");
              for(let j = 0;j<title_name_arr.length;j++){
                $(title_name_arr[j]).attr('title',$(title_name_arr[j]).html());
                // if(_that.getStrL($(title_name_arr[j]).html()) > 20 ){
                // }
              }
            }

					},500)
        })
        .catch(error => {});
    },
    // 判断字符串长度的方法
    getStrL(str){
      let l = str.length; 
      let blen = 0; 
      for(let i=0; i<l; i++) { 
        if ((str.charCodeAt(i) & 0xff00) != 0) { 
          blen ++; 
        } 
        blen ++; 
      }
      return blen;
    },
    //清空筛选条件
    delSelect() {
      this.searchAgentData.dName = "";
      this.searchAgentData.pdName = "";
      this.searchAgentData.distributorId = "";
      this.searchAgentData.state = "";
      this.searchAgentData.startDate = "";
      this.searchAgentData.endDate = "";
      this.searchAgentData.page = 1;
      this.searchAgentData.pageSize=15;
      this.searchInfo =  this.$t('agent.agent');
      this.search(1);
    },
    //搜索
    search(sign,str) {

      // 显示载入提示层
      this.loading = true;

      if(sign === 0) this.searchInfo =  this.$t('index.searchResults');
      const searchData = {};
      $.extend(searchData, this.searchAgentData);
      this.formatObj(searchData);
      // if (searchData.state === this.$t("search.Rejected")) {
      //   searchData.state = 0;
      // }
      // if (searchData.state === this.$t("search.Pending")) {
      //   searchData.state = 1;
      // }
      // if (searchData.state === this.$t("button.Enabled")) {
      //   searchData.state = 2;
      // }
      // if (searchData.state === this.$t("button.Suspended3")) {
      //   searchData.state = 3;
      // }
      this.getAgentList(searchData,str);

      if( str == 'CurrentChange' ){
        // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
        let obj = $('.el-pager .number');
        for( let i = 0; i < obj.length; i++){
            if($(obj[i]).html() == this.oldPage) {
              $(obj[i]).addClass('active');
            } else {
              $(obj[i]).removeClass('active');
            }
        }
      }
    },
    //新增代理商按钮
    showAgentAdd() {
      localStorage.setItem('searchAgentData',JSON.stringify(this.searchAgentData));
      // this.$router.push({ path: "/handleaAgent",query:{ id:'1',name:this.$t('agent.agent'),grade:localStorage.getItem('grade'),page:this.searchAgentData.page,pageSize: this.searchAgentData.pageSize } });
      this.$router.push({ path: "/handleAgent",query:{ id:'1',name:this.$t('agent.agent'),grade:localStorage.getItem('grade') } });
    },
    //代理商详情
    showAgentDtails(id, state,name,grade,parentId) {
      localStorage.setItem('searchAgentData',JSON.stringify(this.searchAgentData));
      // this.$router.push({ path: "/handleaAgent",query:{ id:'2',state:state,disId:id,name:name,grade:grade,parentId:parentId,page:this.searchAgentData.page,pageSize: this.searchAgentData.pageSize } });
      this.$router.push({ path: "/handleAgent",query:{ id:'2',state:state,disId:id,name:name,grade:grade,parentId:parentId } });
    },
    //pageSize 改变时会触发
    handleSizeChange(val) {
      this.searchAgentData.pageSize = val;
      this.search(1);
      // this.$router.push({ path: "/agent", query:{ page:this.searchAgentData.page,pageSize: val } });
    },
    //currentPage 改变时会触发
    handleCurrentChange(val) {
      this.searchAgentData.page = val;
      this.search(1,'CurrentChange');
    },
    formatObj(obj) {
      let arr = Object.keys(obj);
      for (let i = 0; i < arr.length; i++) {
        if (obj[arr[i]] === "") {
          obj[arr[i]] = null;
        }
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/*.shangji{
		width: 300px;
	}*/
</style>
